import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../utils/dio_util.dart';
import '../widget/empty_page.dart';
import '../widget/my_image.dart';
import '../widget/error_page.dart';
import '../widget/my_dialog.dart';

class CategoryPage extends StatefulWidget {
  CategoryPage({Key key}) : super(key: key);

  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage>
    with AutomaticKeepAliveClientMixin {
  int _selectIndex = 0;
  bool isLoaded = false;

  @override
  void initState() {
    super.initState();
  }

  //左侧分类
  Future<Map<String, dynamic>> getCategoryData() async {
    DioUtil dio = DioUtil();
    String api = '/api/mall/product/category/pageList.service';
    Map<String, dynamic> res = await dio.get(api);
    print(res);
    return res;
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    var leftWidth = 750.w / 5;
    var rightWidth = 750.w - 150.w;
    return Scaffold(
        appBar: AppBar(
          centerTitle: true,
          backgroundColor: Colors.white,
          title: Text(
            '产品分类',
            style: TextStyle(
                color: Colors.black,
                fontSize: 30.sp,
                fontWeight: FontWeight.bold),
          ),
        ),
        body: FutureBuilder<Map<String, dynamic>>(
          future: getCategoryData(),
          builder: (context, AsyncSnapshot snapshot) {
            switch (snapshot.connectionState) {
              case ConnectionState.none:
              case ConnectionState.waiting:
                return CustomLoaddingDialog(
                    height: 150.0, width: 150, title: '努力加载中');
                break;
              case ConnectionState.done: // -------- 完成态
                if (snapshot.hasError) {
                  // 异常
                  print(snapshot.error);
                  return ErrorPage(error: snapshot.error.toString());
                } else {
                  // 正常
                  if (snapshot.data['code'] == 200) {
                    var result = snapshot.data['result'];
                    if (result.isEmpty) {
                      return EmptyPage();
                    }
                    return CustomScrollView(
                      physics: BouncingScrollPhysics(),
                      slivers: [
                        SliverToBoxAdapter(
                          child: Container(
                            width: 750.w,
                            padding: EdgeInsets.only(top: 20.h, bottom: 20.h),
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                                color: Colors.white,
                                border: Border(
                                    top: BorderSide(
                                        color: Colors.grey[100], width: 1.0))),
                            child: InkWell(
                              child: Container(
                                width: 650.w,
                                height: 70.h,
                                decoration: BoxDecoration(
                                    color: Colors.grey[100],
                                    borderRadius: BorderRadius.circular(30)),
                                padding: EdgeInsets.only(left: 12),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: <Widget>[
                                    Icon(Icons.search, color: Colors.grey),
                                    SizedBox(width:10.w),
                                    Text("家居用品",
                                        style: TextStyle(fontSize: 25.sp))
                                  ],
                                ),
                              ),
                              onTap: () {
                                Navigator.of(context).pushNamed('/search');
                              },
                            ),
                          ),
                        ),
                        SliverToBoxAdapter(
                          child: RefreshIndicator(
                              displacement: 20,
                              strokeWidth: 4,
                              color: Colors.red,
                              onRefresh: getCategoryData,
                              child: Container(
                                height: 970.h,
                                decoration: BoxDecoration(
                                    color: Colors.white,
                                    border: Border(
                                        top: BorderSide(
                                            color: Colors.grey[100]))),
                                child: Row(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    children: <Widget>[
                                      Container(
                                        width: leftWidth,
                                        height: double.infinity,
                                        color: Colors.grey[100],
                                        child: ListView.separated(
                                          physics: BouncingScrollPhysics(),
                                          separatorBuilder:
                                              (context, int index) {
                                            return Divider(height: 1);
                                          },
                                          itemCount: result.length,
                                          itemBuilder: (context, index) {
                                            return Container(
                                              color: Colors.grey[100],
                                              child: InkWell(
                                                onTap: () {
                                                  setState(() {
                                                    _selectIndex = index;
                                                  });
                                                },
                                                child: Container(
                                                  alignment: Alignment.center,
                                                  width: double.infinity,
                                                  height: 100.w,
                                                  decoration: BoxDecoration(
                                                      color: _selectIndex ==
                                                              index
                                                          ? Colors.white
                                                          : Colors.grey[100],
                                                      border: Border(
                                                          left: BorderSide(
                                                              color: _selectIndex ==
                                                                      index
                                                                  ? Colors.red
                                                                  : Colors
                                                                      .transparent,
                                                              width: 1))),
                                                  child: Text(
                                                    result[index]['cateName'],
                                                    textAlign: TextAlign.center,
                                                    style: TextStyle(
                                                        color: _selectIndex ==
                                                                index
                                                            ? Colors.red
                                                            : Colors.black87,
                                                        fontSize: 28.sp),
                                                  ),
                                                ),
                                              ),
                                            );
                                          },
                                        ),
                                      ),
                                      result[_selectIndex]['children'].length >
                                              0
                                          ? IndexedStack(
                                              index: 0,
                                              children: [
                                                Container(
                                                  width: rightWidth,
                                                  color: Colors.white,
                                                  padding: EdgeInsets.all(20),
                                                  child: ListView(
                                                    physics:
                                                        BouncingScrollPhysics(),
                                                    children: [
                                                      Container(
                                                        width: 250,
                                                        height: 80,
                                                        child: MyImage(
                                                            imgSrc: result[
                                                                    _selectIndex]
                                                                ['pic']),
                                                      ),
                                                      Container(
                                                        width: 250,
                                                        height: 500,
                                                        child: GridView.builder(
                                                            physics:
                                                                BouncingScrollPhysics(),
                                                            padding: EdgeInsets
                                                                .only(top: 50),
                                                            itemCount: result[
                                                                        _selectIndex]
                                                                    ['children']
                                                                .length,
                                                            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                                                                crossAxisCount:
                                                                    3,
                                                                childAspectRatio:
                                                                    0.8,
                                                                crossAxisSpacing:
                                                                    10,
                                                                mainAxisSpacing:
                                                                    15),
                                                            itemBuilder:
                                                                (context,
                                                                    index) {
                                                              return InkWell(
                                                                onTap: () {
                                                                  var categoryId =
                                                                      result[_selectIndex]['children']
                                                                              [
                                                                              index]
                                                                          [
                                                                          'cateId'];
                                                                  print(
                                                                      categoryId);
                                                                  Navigator.of(
                                                                          context)
                                                                      .pushNamed(
                                                                          '/productList',
                                                                          arguments: {
                                                                        "categoryId":
                                                                            categoryId,
                                                                            "categoryName":result[_selectIndex]['children'][index]['cateName']
                                                                      });
                                                                },
                                                                child: Column(
                                                                  children: [
                                                                    Container(
                                                                        width:
                                                                            70,
                                                                        child:
                                                                            MyImage(
                                                                          imgSrc:
                                                                              result[_selectIndex]['children'][index]['pic'],
                                                                        )),
                                                                    SizedBox(
                                                                        height:
                                                                            5),
                                                                    Text(
                                                                      result[_selectIndex]['children']
                                                                              [
                                                                              index]
                                                                          [
                                                                          'cateName'],
                                                                      style: TextStyle(
                                                                          fontSize:
                                                                              13,
                                                                          color:
                                                                              Colors.black54),
                                                                    )
                                                                  ],
                                                                ),
                                                              );
                                                            }),
                                                      )
                                                    ],
                                                  ),
                                                )
                                              ],
                                            )
                                          : Container(
                                              width: rightWidth,
                                              height: double.infinity,
                                              child: EmptyPage()),
                                    ]),
                              )),
                        )
                      ],
                    );
                  } else if (snapshot.data['code'] != 200) {
                    return ErrorPage(error: snapshot.data['msg']);
                  }
                }
                break;
              default:
                break;
            }
          },
        ));
  }

  @override
  bool get wantKeepAlive => true;
}
